package com.duoduo.springcloud.controller;

import com.duoduo.springcloud.entities.CommonResult;
import com.duoduo.springcloud.entities.Payment;
import com.duoduo.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * PaymentController
 *
 * @author qian
 * @version 1.0
 * @date 2020/11/17 11:22
 */
@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private Integer serverPort;

    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("*****插入结果：" + result);
        if (result > 0) {  //成功
            return new CommonResult(200, "插入数据库成功,端口:" + serverPort, result);
        } else {
            return new CommonResult(444, "插入数据库失败,端口:" + serverPort, null);
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("*****查询结果：" + payment);
        if (payment != null) {  //说明有数据，能查询成功
            return new CommonResult(200, "查询成功,端口:" + serverPort, payment);
        } else {
            return new CommonResult(444, "没有对应记录，查询ID：" + id + ",端口:" + serverPort, null);
        }
    }

    @GetMapping(value = "/payment/discovery")
    public CommonResult getDiscovery(){
        List<String> services = discoveryClient.getServices();
        services.stream().forEach(service->log.info("****service:"+service));
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-PAYMENT");
        instances.stream().forEach(instance->log.info("serviceId:{},host:{},port:{},uri:{}",instance.getServiceId(),instance.getHost(),instance.getPort(),instance.getUri()));
        return new CommonResult(200, "查询成功,端口:" + serverPort, this.discoveryClient);
    }

    @GetMapping(value = "/payment/lb")
    public String getlb(){
        return serverPort.toString();
    }

    @GetMapping(value = "/payment/timeout")
    public String timeout(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort.toString();
    }

}
